﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;

namespace ViewComponents.Behaviours
{
    public static class OnLoadedBehaviour
    {
        public static ICommand GetOnLoadedCommand(DependencyObject obj)
        {
            return (ICommand)obj.GetValue(OnLoadedCommandProperty);
        }

        public static void SetOnLoadedCommand(DependencyObject obj, ICommand value)
        {
            obj.SetValue(OnLoadedCommandProperty, value);
        }

        public static readonly DependencyProperty OnLoadedCommandProperty =
                DependencyProperty.RegisterAttached("OnLoadedCommand", typeof(ICommand), typeof(OnLoadedBehaviour),
                 new UIPropertyMetadata(null, OnLoadedCommandPropertyChanged));


        static void OnLoadedCommandPropertyChanged(DependencyObject d,
                DependencyPropertyChangedEventArgs e)
        {
            ((FrameworkElement)d).Loaded += new RoutedEventHandler(element_Loaded);
        }

        static void element_Loaded(object sender, RoutedEventArgs e)
        {
            FrameworkElement element = ((FrameworkElement)sender);
            ICommand command = GetOnLoadedCommand(element);
            if (command.CanExecute(null))
                command.Execute(null);
            
            element.Loaded -= new RoutedEventHandler(element_Loaded);
        }
    }
}
